#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import json, time
from aiohttp import web
from aioweb import corelib

import db, main


routes = web.RouteTableDef()
module_name = 'clipboard'

@routes.get('/%s' % module_name)
@corelib.template('clipboard.html')
async def records_index(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        path = params.get('path', '/root')
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
    return data

@routes.get('/%s/items' % module_name)
async def clipboard_items(request):
    data = {}
    try:
        params = await corelib.parse_param(request)
        index = int(params.get('index', '1'))
        pagesize = int(params.get('pagesize', '36'))
        session = db.create_session()
        items = await main.load_items('Clipboard', order_by={'id': False})
        data = dict(data, **items)
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        data['items'] = []
    return web.json_response({'code': 0, 'msg': data})


@routes.post('/clipboard')
async def save_clipboard(request):
    try:
        params = await corelib.parse_param(request)
        text = params.get('text', '')
        if not text or not text.strip():
            return {'code': -1, 'field': 'text', 'msg': 'text is null'}
        session = db.create_session()
        user = request.__user__
        if user:
            clipboard = db.Clipboard(content=text, user_id=user.id)
        else:
            clipboard = db.Clipboard(content=text, user_id=0)
        session.add(clipboard)
        session.commit()
        data = {'code': 0, 'msg': clipboard.id}
        return data
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return {'code': -1, 'msg': str(e)}

@routes.get('/clipboard/delete/{id}')
async def delete_clipboard(request):
    try:
        id = request.match_info['id']
        session = db.create_session()
        item = session.query(db.Clipboard).filter(db.Clipboard.id==id).first()
        if not item:
            return {'code': -1, 'msg': '[%s]不存在' % id}
        session.delete(item)
        session.commit()
        return {'code': 0, 'msg': '删除[%s]成功' % id}
    except BaseException as e:
        logging.error('\n%s' % corelib.printException(e))
        return {'code': -1, 'msg': str(e)}
